/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * InvoiceSummaryPane.java
 *
 * Created on 24-jul-2010, 12:29:18
 */
package facturasapp;

import facturasapp.data.DataManager;
import facturasapp.data.FileManager;
import facturasapp.data.HTMLManager;
import facturasapp.data.StoreManager;
import facturasapp.events.FacturaAdapter;
import facturasapp.events.FacturaEvent;
import facturasapp.events.EventManager;
import facturasapp.events.FacturaListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import storeDataModel.Invoice;
import storeDataModel.ProductRelation;

/**
 *
 * @author CiberXtrem
 */
public class InvoiceSummaryPane extends javax.swing.JPanel {

    /** Creates new form InvoiceSummaryPane */
    public InvoiceSummaryPane() {
        initComponents();
        initCustomComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        baseImpLabel = new javax.swing.JLabel();
        totalImporteField = new javax.swing.JTextField();
        porcentajeIvaLabel = new javax.swing.JLabel();
        porcentIvaField = new javax.swing.JTextField();
        ImpIvaLabel = new javax.swing.JLabel();
        impIvaField = new javax.swing.JTextField();
        totalFactLabel = new javax.swing.JLabel();
        totalFactField = new javax.swing.JTextField();
        GuardarButton = new javax.swing.JButton();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(facturasapp.FacturasApp.class).getContext().getResourceMap(InvoiceSummaryPane.class);
        baseImpLabel.setFont(resourceMap.getFont("baseImpLabel.font")); // NOI18N
        baseImpLabel.setText(resourceMap.getString("baseImpLabel.text")); // NOI18N
        baseImpLabel.setName("baseImpLabel"); // NOI18N

        totalImporteField.setText(resourceMap.getString("totalImporteField.text")); // NOI18N
        totalImporteField.setName("totalImporteField"); // NOI18N

        porcentajeIvaLabel.setFont(resourceMap.getFont("porcentajeIvaLabel.font")); // NOI18N
        porcentajeIvaLabel.setText(resourceMap.getString("porcentajeIvaLabel.text")); // NOI18N
        porcentajeIvaLabel.setName("porcentajeIvaLabel"); // NOI18N

        porcentIvaField.setText(resourceMap.getString("porcentIvaField.text")); // NOI18N
        porcentIvaField.setName("porcentIvaField"); // NOI18N
        porcentIvaField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                porcentIvaFieldActionPerformed(evt);
            }
        });
        porcentIvaField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                porcentIvaFieldFocusLost(evt);
            }
        });

        ImpIvaLabel.setFont(resourceMap.getFont("ImpIvaLabel.font")); // NOI18N
        ImpIvaLabel.setText(resourceMap.getString("ImpIvaLabel.text")); // NOI18N
        ImpIvaLabel.setName("ImpIvaLabel"); // NOI18N

        impIvaField.setText(resourceMap.getString("impIvaField.text")); // NOI18N
        impIvaField.setName("impIvaField"); // NOI18N

        totalFactLabel.setFont(resourceMap.getFont("totalFactLabel.font")); // NOI18N
        totalFactLabel.setText(resourceMap.getString("totalFactLabel.text")); // NOI18N
        totalFactLabel.setName("totalFactLabel"); // NOI18N

        totalFactField.setText(resourceMap.getString("totalFactField.text")); // NOI18N
        totalFactField.setName("totalFactField"); // NOI18N

        GuardarButton.setIcon(resourceMap.getIcon("GuardarButton.icon")); // NOI18N
        GuardarButton.setText(resourceMap.getString("GuardarButton.text")); // NOI18N
        GuardarButton.setName("GuardarButton"); // NOI18N
        GuardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GuardarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(baseImpLabel)
                    .addComponent(totalImporteField, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(porcentajeIvaLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(porcentIvaField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ImpIvaLabel)
                    .addComponent(impIvaField, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(totalFactField)
                    .addComponent(totalFactLabel))
                .addGap(18, 18, 18)
                .addComponent(GuardarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(GuardarButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(ImpIvaLabel)
                                .addComponent(totalFactLabel))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(totalFactField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(impIvaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(porcentajeIvaLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(porcentIvaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(baseImpLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(totalImporteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void GuardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarButtonActionPerformed
        Invoice invoice = (Invoice) DataManager.getInstance().getDataObject("currentInvoice");
        //Save in database
        //Invoice detachedInvoice = null;
        try {
             EventManager.getInstance().fireFacturaEvent(new FacturaEvent(invoice), EventManager.INVOICE_STORED);
            //Hacemos persistente la factura
            PersistenceManagerFactory pmf = StoreManager.get();
            PersistenceManager pm = pmf.getPersistenceManager();
            pm.currentTransaction().begin();

            System.out.println("Before persistence: Invoice: " + invoice);
            pm.makePersistent(invoice);
            System.out.println("After persistence in transition: Invoice: " + invoice);

            //pm.getFetchPlan().addGroup("detach_productsRelation");
            //pm.getFetchPlan().addGroup("detach_product");
            //pm.getFetchPlan().setMaxFetchDepth(2);
            //detachedInvoice = pm.detachCopy(invoice);

             //Pring history
            try {
                HTMLManager.generateHistory(invoice, "history\\" + invoice.getId() + ".html");
            } catch (Exception ex) {
                Logger.getLogger(InvoiceSummaryPane.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            pm.currentTransaction().commit();
            pm.close();

        } catch (Exception e) {
            e.printStackTrace();
             //Pring history
            try {
                HTMLManager.generateHistory(invoice, "history\\" + invoice.getId() + ".html");
            } catch (Exception ex) {
                Logger.getLogger(InvoiceSummaryPane.class.getName()).log(Level.SEVERE, null, ex);
            }

             EventManager.getInstance().fireFacturaEvent(new FacturaEvent(invoice), EventManager.INVOICE_STORED);
        }
        finally{
           //Create new Invoice
            invoice = new Invoice("sin matricula");
            DataManager.getInstance().addDataObject("currentInvoice", invoice);

            System.out.println("New Invoice, number of elements: " + invoice.getProductRelations().size());
        }
        //Mensage para iniciar nueva factura
        /*JFrame frame = new JFrame();
        int userOutput = JOptionPane.showOptionDialog(frame, "Iniciar nueva factura?", "Nueva factura",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

        if(userOutput == 0){
            EventManager.getInstance().fireFacturaEvent(new FacturaEvent(invoice), EventManager.NEW_INVOICE);
        }
        else{
            //indicamos que la factura ya esta almacenada (se tendra que bloquear el panel)
             EventManager.getInstance().fireFacturaEvent(new FacturaEvent(invoice), EventManager.INVOICE_STORED);
        }
         */
    }//GEN-LAST:event_GuardarButtonActionPerformed

    private void porcentIvaFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_porcentIvaFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_porcentIvaFieldActionPerformed

    private void porcentIvaFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_porcentIvaFieldFocusLost
        EventManager.getInstance().fireFacturaEvent(new FacturaEvent(this), EventManager.INVOICE_UPDATED);
    }//GEN-LAST:event_porcentIvaFieldFocusLost

    public void initCustomComponents() {
        //Init Values
        Properties props = (Properties) DataManager.getInstance().getDataObject("invoiceProperties");
        String porcentageIva = props.getProperty("iva") == null ? porcentIvaField.getText() : props.getProperty("iva");
        porcentIvaField.setText(porcentageIva);
        

        //Listener
        EventManager.getInstance().addFacturaListener(new FacturaAdapter() {

            @Override
            public void invoiceUpdated(FacturaEvent e) {
                //Hacer resumen
                Invoice invoice = (Invoice) DataManager.getInstance().getDataObject("currentInvoice");
                Iterator it = invoice.getProductRelations().iterator();

                float totalBaseImponible = 0.00f;
                while (it.hasNext()) {

                    ProductRelation productRelation = (ProductRelation) it.next();
                    //System.out.println("sumando:" + productRelation);
                    totalBaseImponible += productRelation.getImporte();
                }
                invoice.setBaseImponible(Math.round(totalBaseImponible * 100.0f) / 100.0f);

                float porcentageIva = Float.valueOf(porcentIvaField.getText()) / 100.0f;
                invoice.setIva(porcentageIva);

                float importeIva = totalBaseImponible * porcentageIva;
                invoice.setImporteIva((float) (Math.round(importeIva * 100.0f) / 100.0f));

                float totalFactura = totalBaseImponible + importeIva;
                invoice.setTotal((float) (Math.round(totalFactura * 100.0f) / 100.0f));

                //Update Visual Data
                totalImporteField.setText(String.valueOf((float) (Math.round(totalBaseImponible * 100.0f) / 100.0f)));
                impIvaField.setText(String.valueOf((float) (Math.round(importeIva * 100.0f) / 100.0f)));
                totalFactField.setText(String.valueOf((float) (Math.round(totalFactura * 100.0f) / 100.0f)));

                //Save Invoice (iva) properties
                Properties props = (Properties) DataManager.getInstance().getDataObject("invoiceProperties");
                props.setProperty("iva", porcentIvaField.getText());

                try {
                    props.store(new FileOutputStream("facturasBuilder.properties"), null);
                } catch (Exception ex) {
                    Logger.getLogger(InvoiceSummaryPane.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            public void newInvoice(FacturaEvent e) {
                System.out.println("New invoice received");
                reset();
            }
        });
    }

    public void reset(){
        impIvaField.setText("");
        totalFactField.setText("");
        totalImporteField.setText("");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton GuardarButton;
    private javax.swing.JLabel ImpIvaLabel;
    private javax.swing.JLabel baseImpLabel;
    private javax.swing.JTextField impIvaField;
    private javax.swing.JTextField porcentIvaField;
    private javax.swing.JLabel porcentajeIvaLabel;
    private javax.swing.JTextField totalFactField;
    private javax.swing.JLabel totalFactLabel;
    private javax.swing.JTextField totalImporteField;
    // End of variables declaration//GEN-END:variables
    //Custom Variables
    Invoice invoice = null;
    //End Custom Variables
}
